package com.dd.controller;

import com.dd.model.Order;
import com.dd.model.OrderItem;
import com.dd.service.DeliveryService;
import com.dd.service.OrderService;
import com.dd.service.ProductStatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/orders")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ProductStatService productStatService;

    @Autowired
    private DeliveryService deliveryService;
    
    /**
     * 获取所有订单
     */
    @GetMapping
    public ResponseEntity<List<Order>> getAllOrders() {
        List<Order> orders = orderService.findAllOrders();
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据ID获取订单
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getOrder(@PathVariable("id") Integer id) {
        Order order = orderService.getOrderById(id);
        if (order == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "订单不存在");
            return ResponseEntity.badRequest().body(response);
        }
        return ResponseEntity.ok(order);
    }
    
    /**
     * 根据客户ID获取订单
     */
    @GetMapping("/customer/{customerId}")
    public ResponseEntity<List<Order>> getOrdersByCustomer(@PathVariable("customerId") Integer customerId) {
        List<Order> orders = orderService.findOrdersByCustomer(customerId);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 根据订单状态获取订单
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Order>> getOrdersByStatus(@PathVariable("status") String status) {
        List<Order> orders = orderService.findOrdersByStatus(status);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 创建订单
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createOrder(@RequestBody Map<String, Object> orderData) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 解析订单数据
            Order order = new Order();
            order.setCustomerId((Integer) orderData.get("customerId"));
            
            // 处理totalAmount的类型转换问题
            Object totalAmountObj = orderData.get("totalAmount");
            BigDecimal totalAmount;
            if (totalAmountObj instanceof Integer) {
                totalAmount = new BigDecimal((Integer) totalAmountObj);
            } else if (totalAmountObj instanceof Double) {
                totalAmount = BigDecimal.valueOf((Double) totalAmountObj);
            } else if (totalAmountObj instanceof String) {
                totalAmount = new BigDecimal((String) totalAmountObj);
            } else {
                totalAmount = BigDecimal.valueOf(Double.parseDouble(totalAmountObj.toString()));
            }
            order.setTotalAmount(totalAmount);
            
            // 设置订单状态
            if (orderData.containsKey("status")) {
                order.setStatus((String) orderData.get("status"));
            }
            
            // 解析订单项
            List<Map<String, Object>> itemsData = (List<Map<String, Object>>) orderData.get("items");
            List<OrderItem> orderItems = new java.util.ArrayList<>();
            
            for (Map<String, Object> itemData : itemsData) {
                OrderItem item = new OrderItem();
                item.setProductId((Integer) itemData.get("productId"));
                item.setQuantity((Integer) itemData.get("quantity"));
                
                // 处理unitPrice的类型转换问题
                if (itemData.containsKey("unitPrice")) {
                    Object unitPriceObj = itemData.get("unitPrice");
                    BigDecimal unitPrice;
                    if (unitPriceObj instanceof Integer) {
                        unitPrice = new BigDecimal((Integer) unitPriceObj);
                    } else if (unitPriceObj instanceof Double) {
                        unitPrice = BigDecimal.valueOf((Double) unitPriceObj);
                    } else if (unitPriceObj instanceof String) {
                        unitPrice = new BigDecimal((String) unitPriceObj);
                    } else {
                        unitPrice = BigDecimal.valueOf(Double.parseDouble(unitPriceObj.toString()));
                    }
                    item.setUnitPrice(unitPrice);
                }
                
                orderItems.add(item);
            }
            
            // 创建订单
            boolean result = orderService.createOrder(order, orderItems);
            
            if (result) {
                response.put("success", true);
                response.put("message", "创建订单成功");
                response.put("orderId", order.getOrderId());
                
                // 更新商品销售统计
                for (OrderItem item : orderItems) {
                    productStatService.updateProductSaleStats(item.getProductId(), item.getQuantity());
                }
            } else {
                response.put("success", false);
                response.put("message", "创建订单失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建订单失败: " + e.getMessage());
            e.printStackTrace(); // 添加详细日志输出
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新订单状态
     */
    @PutMapping("/{id}/status/{status}")
    public ResponseEntity<Map<String, Object>> updateOrderStatus(@PathVariable("id") Integer id,
                                                                @PathVariable("status") String status) {
        Map<String, Object> response = new HashMap<>();
        boolean result = orderService.updateOrderStatus(id, status);
        
        if (result) {
            response.put("success", true);
            response.put("message", "更新订单状态成功");
        } else {
            response.put("success", false);
            response.put("message", "更新订单状态失败，订单可能不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 删除订单
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteOrder(@PathVariable("id") Integer id) {
        Map<String, Object> response = new HashMap<>();
        deliveryService.deleteDeliveryByOrderId(id);
        boolean result = orderService.deleteOrder(id);
        
        if (result) {
            response.put("success", true);
            response.put("message", "删除订单成功");
        } else {
            response.put("success", false);
            response.put("message", "删除订单失败，订单可能不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取订单项
     */
    @GetMapping("/{orderId}/items")
    public ResponseEntity<List<OrderItem>> getOrderItems(@PathVariable("orderId") Integer orderId) {
        List<OrderItem> items = orderService.getOrderItems(orderId);
        return ResponseEntity.ok(items);
    }
    
    /**
     * 添加订单项
     */
    @PostMapping("/{orderId}/items")
    public ResponseEntity<Map<String, Object>> addOrderItem(@PathVariable("orderId") Integer orderId,
                                                           @RequestBody OrderItem orderItem) {
        Map<String, Object> response = new HashMap<>();
        
        // 设置订单ID
        orderItem.setOrderId(orderId);
        
        boolean result = orderService.addOrderItem(orderItem);
        
        if (result) {
            response.put("success", true);
            response.put("message", "添加订单项成功");
            response.put("itemId", orderItem.getItemId());
            
            // 更新商品销售统计
            productStatService.updateProductSaleStats(orderItem.getProductId(), orderItem.getQuantity());
        } else {
            response.put("success", false);
            response.put("message", "添加订单项失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新订单项
     */
    @PutMapping("/{orderId}/items/{itemId}")
    public ResponseEntity<Map<String, Object>> updateOrderItem(@PathVariable("orderId") Integer orderId,
                                                              @PathVariable("itemId") Integer itemId,
                                                              @RequestBody OrderItem orderItem) {
        Map<String, Object> response = new HashMap<>();
        
        // 设置ID
        orderItem.setOrderId(orderId);
        orderItem.setItemId(itemId);
        
        boolean result = orderService.updateOrderItem(orderItem);
        
        if (result) {
            response.put("success", true);
            response.put("message", "更新订单项成功");
        } else {
            response.put("success", false);
            response.put("message", "更新订单项失败，订单项可能不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 删除订单项
     */
    @DeleteMapping("/{orderId}/items/{itemId}")
    public ResponseEntity<Map<String, Object>> deleteOrderItem(@PathVariable("orderId") Integer orderId,
                                                             @PathVariable("itemId") Integer itemId) {
        Map<String, Object> response = new HashMap<>();
        boolean result = orderService.deleteOrderItem(itemId);
        
        if (result) {
            response.put("success", true);
            response.put("message", "删除订单项成功");
        } else {
            response.put("success", false);
            response.put("message", "删除订单项失败，订单项可能不存在");
        }
        
        return ResponseEntity.ok(response);
    }
} 